<?php

namespace app\controller;

use app\service\UserService;
use support\Response;

//登录控制器
class LoginController extends Base
{

    /**
     * 不需要登录的方法
     */
    protected array $noNeedLogin = ['index'];

    //登录
    public function index(): Response
    {
        //platform 0:测试环境 1:微信小程序 2:手机号 验证码登录
        //小程序登录code
        $code = $this->request->post('code', '10001');
        //获取参数platform
        $platform = $this->request->post('platform', 0);
        //手机号
        $mobile = $this->request->post('mobile', 0);
        //短信验证码
        $sms_code = $this->request->post('sms_code', '');


        // 启动事务
        $this->db::startTrans();

        try {
            $userService = new UserService();
            switch ($platform) {
                case 0://h5
                    $res = $userService->toLoginByCode($code, $platform);
                    break;
                case 1: //1微信小程序登陆
                    $res = $userService->toLoginByCode($code, $platform);
                    break;
                case 2://手机号验证码登录
                    $res = $userService->toLoginByMobileAndSmsCode($mobile, $sms_code,$platform);
                    break;
                default:
                    $this->db::rollBack();
                    return json(apiError('暂不支持的登录方式'));
            }

            if ($res['code']) {
                $token = $res['data']['token'];
                if (!$token) {
                    $this->db::rollBack();
                    return json(apiError('登录失败'));
                }
                $this->db::commit();
            } else {
                $this->db::rollBack();
            }
            return json($res);

        } catch (\Exception $e) {
            $this->db::rollBack();
            throw $e;
        }
    }

}
